﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Net;
using System.Net.Sockets;

namespace CSharpClient
{
	public class ServerClient
	{
		private const int BufferSize = 8192;
		private byte[] buffer;
		private TcpClient client;
		private NetworkStream stream;
		private string msg = "Welcome to CSharp Network";
		private IPAddress ip = IPAddress.Parse("192.168.144.2");
		private int port = 8500;

		public ServerClient()
		{
			try
			{
				client = new TcpClient();
				client.Connect(ip, port);
			}
			catch (System.Exception ex)
			{
				Console.WriteLine(ex.Message);
				return;
			}

			buffer = new byte[BufferSize];

			Console.WriteLine("Server Connected!{0} --> {1}",
								client.Client.LocalEndPoint,
								client.Client.RemoteEndPoint);
			stream = client.GetStream();
		}

		public void SendMessage(string msg)
		{
			msg = String.Format("[length={0}]{1}",msg.Length,msg);

			for (int i = 0; i < 3; ++i )
			{
				byte[] temp = Encoding.Unicode.GetBytes(msg);
				try
				{
					stream.Write(temp, 0, temp.Length);
					Console.WriteLine("Sent: {0}", msg);
				}
				catch (System.Exception ex)
				{
					Console.WriteLine(ex.Message);
					break;
				}
			}

			lock (stream)
			{
				AsyncCallback callBack = new AsyncCallback(ReadComplete);
				stream.BeginRead(buffer, 0, BufferSize, callBack, null);
			}
		}

		public void SendMessage()
		{
			SendMessage(this.msg);
		}

		public void ReadComplete(IAsyncResult ar)
		{
			int bytesRead;

			try
			{
				lock(stream)
				{
					bytesRead = stream.EndRead(ar);
				}

				if (bytesRead == 0)
				{
					throw new Exception("读到0字节");
				}

				string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);

				Console.WriteLine("Received: {0}", msg);
				Array.Clear(buffer, 0, buffer.Length);

				lock (stream)
				{
					AsyncCallback callBack = new AsyncCallback(ReadComplete);
					stream.BeginRead(buffer, 0, BufferSize, callBack, null);
				}
			}
			catch (System.Exception ex)
			{
				if (stream != null)
				{
					stream.Dispose();
				}
				client.Close();

				Console.WriteLine(ex.Message);
			}
		}

	}
	class Client
	{
		static void Main(string[] args)
		{
			Console.WriteLine("Client Running ...");

			//IPAddress ip = IPAddress.Parse("192.168.144.2");
			//int port = 8500;

			//TcpClient client = new TcpClient();
			//try
			//{
			//    client.Connect(ip, port);
			//}
			//catch (System.Exception ex)
			//{
			//    Console.WriteLine(ex.Message);
			//    return;
			//}

			//Console.WriteLine("Server Connected! {0} --> {1}",
			//    client.Client.LocalEndPoint, client.Client.RemoteEndPoint);

			//NetworkStream stream = client.GetStream();
			//String msg = "How are you";
			//byte[] buffer = Encoding.Unicode.GetBytes(msg);
			//stream.Write(buffer, 0, buffer.Length);


			//Console.WriteLine("Sent: {0}", msg);

			ServerClient client = new ServerClient();
			client.SendMessage();


			ConsoleKey key;
			do
			{
				key = Console.ReadKey(true).Key;
			} while (key != ConsoleKey.Q);
		}
	}
}
